package com.ssj.ssj.modules.security.services;

import com.ssj.ssj.modules.man.entity.SUser;
import com.ssj.ssj.modules.man.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

  @Autowired
  SUserService dao;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    SUser sysUser = dao.getByUsername(username);
    if (sysUser == null) {
      throw new UsernameNotFoundException("用户名或密码错误");
    }
    return new AccountUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getId()));

  }

  /**
   * 获取用户ID获取 权限信息（角色、菜单权限）
   * @param userId
   * @return
   */
  public List<GrantedAuthority> getUserAuthority(Integer userId) {
    List<String> authorityList = dao.getUserAuthorityInfo(userId);
    String[] authority = authorityList.toArray(new String[authorityList.size()]);

    return AuthorityUtils.createAuthorityList(authority);
  }
}
